package com.zhao.fishingguideserver.service.impl;

import com.zhao.fishingguideserver.POJO.AdminUser;
import com.zhao.fishingguideserver.mapper.AdminUserMapper;
import com.zhao.fishingguideserver.service.AdminAuthService;
import com.zhao.fishingguideserver.utils.JwtUtil;
import com.zhao.fishingguideserver.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员认证服务实现类
 */
@Service
public class AdminAuthServiceImpl implements AdminAuthService {
    
    @Autowired
    private AdminUserMapper adminUserMapper;
    
    @Override
    public String login(String username, String password) {
        // 根据用户名查询管理员
        AdminUser adminUser = adminUserMapper.selectByUsername(username);
        
        if (adminUser == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证状态
        if (adminUser.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 验证密码（假设密码已经MD5加密）
        String md5Password = Md5Util.getMD5String(password);
        if (!md5Password.equals(adminUser.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成JWT Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", adminUser.getAdminId());
        claims.put("username", adminUser.getUsername());
        claims.put("role", adminUser.getRole());
        
        return JwtUtil.genToken(claims);
    }
    
    @Override
    public AdminUser findByUsername(String username) {
        return adminUserMapper.selectByUsername(username);
    }
    
    @Override
    public AdminUser findById(Long adminId) {
        return adminUserMapper.selectById(adminId);
    }
}

